#1 存储二维数据
def my_write_table():
    lst = [
        ['商品名称', '单价', '采购数量'],
        ['水杯', '98', '20'],
        ['鼠标', '78', '100']
    ]   # 元素必须都是字符串
    with open('table.csv', 'w', encoding='utf-8') as file:
        # 循环写入
        for item in lst:
            line = ','.join(item)
            file.write(line)
            file.write('\n')
def my_read_table():
    data = []
    with open('table.csv', 'r', encoding='utf-8') as file:
        lst = file.readlines()
        print(lst)
        for item in lst:
            new_lst = item[: len(item)-1].split(',')
            data.append(new_lst)
    print(data)

if __name__ == '__main__':
    my_write_table()
    my_read_table()

#2 高维数据的存储
import json
lst2 = [
    {'name': 'zw', 'age': 18, 'score': 90},
    {'name': 'hmm', 'age': 21, 'score': 99},
    {'name': 'zyy', 'age': 19, 'score': 87},
]
# 编码过程，将list格式转换为string
str2 = json.dumps(lst2 , ensure_ascii=False, indent=4) # ensure_ascii正常显示中文；indent缩进格式，用于美观
print(type(str2),str2)

# 解码
lst3 = json.loads((str2))
print(type(lst3),lst3)

# 编码到文件中
with open('student.txt', 'w', encoding='utf-8') as file:
    json.dump(lst2, file, ensure_ascii=False, indent=4)

# 解码到程序
with open('student.txt', 'r', encoding='utf-8') as file:
    lst4 = json.load(file)
    print(lst4)
